package alipay.openplatform.edu.campus.jiuye.service.services.topic;

import alipay.openplatform.edu.campus.jiuye.common.cache.CacheManagerService;
import alipay.openplatform.edu.campus.jiuye.common.enums.TopicInfoEnum;
import alipay.openplatform.edu.campus.jiuye.common.enums.TopicInfoStateEnum;
import alipay.openplatform.edu.campus.jiuye.common.exception.OnlineRuntimeException;
import alipay.openplatform.edu.campus.jiuye.common.page.Page;
import alipay.openplatform.edu.campus.jiuye.common.utils.CopyVoPo;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.dao.mappers.topic.TopicInfoMapper;
import alipay.openplatform.edu.campus.jiuye.model.po.TopicInfoImgPO;
import alipay.openplatform.edu.campus.jiuye.model.po.TopicInfoPO;
import alipay.openplatform.edu.campus.jiuye.model.vo.*;
import alipay.openplatform.edu.campus.jiuye.service.iservice.topic.*;
import alipay.openplatform.edu.campus.jiuye.service.services.system.AreaInfoService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;


@Service
public class TopicInfoService implements ITopicInfoService {
    private final static Logger log = LoggerFactory.getLogger(TopicInfoService.class);
    @Autowired
    private TopicInfoMapper topicInfoMapper;
    @Autowired
    private ITopicDetailInfoService iTopicDetailInfoService;
    @Autowired
    private ITopicImgInfoService iTopicImgInfoService;
    @Autowired
    private ITopicCityInfoService iTopicCityInfoService;
    @Autowired
    private ITopicSchoolInfoService iTopicSchoolInfoService;
    @Autowired
    private CacheManagerService cacheManagerService;
    @Autowired
    private AreaInfoService areaInfoService;

    transient final ReentrantLock lock = new ReentrantLock();

    private final static Integer DATAFROMDB = 50;
    private final static String JIUYE = "jiuye:";

    public int deleteByPrimaryKey(Integer topicId) {
        return 0;
    }

    public int insert(TopicInfoPO record) {
        return topicInfoMapper.insert(record);
    }

    public int insertSelective(TopicInfoPO record) {
        return 0;
    }

    public TopicInfoPO selectByPrimaryKey(Integer topicId) {
        log.info("查看主题信息[TopicInfoService][selectByPrimaryKey]param{topicId :" + topicId + "}");
        if (ObjectUtils.isEmpty(topicId)) {
            log.error("[TopicInfoService][selectByPrimaryKey()] check topicId is NULL");
            throw new OnlineRuntimeException("PARAM_ERROR", "参数不合法");
        }
        TopicInfoPO topicInfoPO = topicInfoMapper.selectByPrimaryKey(topicId);


        return topicInfoPO;
    }

    public int updateByPrimaryKeySelective(TopicInfoPO record) {
        return 0;
    }

    public int updateByPrimaryKey(TopicInfoPO record) {
        return 0;
    }

    /**
     * 通过主题名称喝状态查询
     *
     * @param page topic_title
     * @param page timeState
     * @param page topicType
     * @param page pageNo
     * @param page pageSize
     * @return
     */
    public Page<Object> selectTopicInfoPOByTitleAndStatus(Page page) {
        log.info("查看主题信息[TopicInfoService][selectTopicInfoPOByTitleAndStatus]param{page :" + page + "}");
        if (ObjectUtils.hasEmpty(page)) {
            log.error("[TopicInfoService][selectTopicInfoPOByTitleAndStatus()] check page is NULL");
            throw new OnlineRuntimeException("PARAM_ERROR", "参数不合法");
        }
        //1创建一个list集合,存储集合
        List<TopicInfoPO> listTopicInfo = topicInfoMapper.selectTopicInfoPOByTitleAndStatus(page);
        if (listTopicInfo == null) {
            log.info("[TopicInfoService][selectTopicInfoPOByTitleAndStatus()] check listTopicInfo is NULL");
            return page;
        }
        List<TopicInfoVO> listTopicInfoVO = CopyVoPo.copyList(listTopicInfo, TopicInfoVO.class);
        for (TopicInfoVO topicInfoVO : listTopicInfoVO) {
            //按照主题类型分类
            if (page.getParams().get("topicType") != "" && page.getParams().get("topicType") != null) {
                topicInfoVO.setTopicName(TopicInfoEnum.getMessage(Integer.parseInt(String.valueOf(page.getParams().get("topicType")))));
            } else {
                topicInfoVO.setTopicName(TopicInfoEnum.getMessage(topicInfoVO.getTopicType()));
            }
            if (page.getParams().get("timeState") != "" && page.getParams().get("timeState") != null) {
                topicInfoVO.setStatus(TopicInfoStateEnum.getMessage(Integer.parseInt(String.valueOf(page.getParams().get("timeState")))));
            } else {
                if (topicInfoVO.getStarttime().before(new Date()) || topicInfoVO.getState() == 1) {
                    topicInfoVO.setStatus(TopicInfoStateEnum.END.getMessage());
                } else if (topicInfoVO.getStarttime().after(new Date()) && topicInfoVO.getState() == 0) {
                    topicInfoVO.setStatus(TopicInfoStateEnum.START.getMessage());
                }
            }
            //判断是否删除
            if(topicInfoVO.getIfDel()){
                topicInfoVO.setStatus(TopicInfoStateEnum.DELETE.getMessage());
            }

            //判断是否过期  未开始  还是默认全部查询
//            if (page.getParams().get("timeState").toString().equals("1")) {
//                topicInfoVO.setStatus(TopicInfoStateEnum.END.getMessage());
//            } else if (page.getParams().get("timeState").toString().equals("0")) {
//                topicInfoVO.setStatus(TopicInfoStateEnum.START.getMessage());
//            } else {
//                if (topicInfoVO.getStarttime().before(new Date())) {
//                    topicInfoVO.setStatus(TopicInfoStateEnum.END.getMessage());
//                } else {
//                    topicInfoVO.setStatus(TopicInfoStateEnum.START.getMessage());
//                }
//            }
        }
        page.setResults(listTopicInfoVO);
        log.info("查看主题信息[TopicInfoService][selectTopicInfoPOByTitleAndStatus]param{page :" + JSON.toJSONString(page) + "}");
        return page;
    }


    /**
     * 添加主題
     *
     * @param createmanId 当前用户
     * @param topicInfoVO 参数对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void addTopic(Integer createmanId, TopicInfoVO topicInfoVO) {
        log.info("添加主题|TopicInfoService|addTopic|params:createmanId={},topicInfoVO={}", createmanId, topicInfoVO);
        //获取参数并验证非空
        Integer topicType = topicInfoVO.getTopicType();
        String topicTitle = topicInfoVO.getTopicTitle();
        Integer ifLine = topicInfoVO.getIfLine();
        Date startTime = topicInfoVO.getStarttime();
        String place = topicInfoVO.getPlace();
        String content = topicInfoVO.getContent();
        if (ObjectUtils.hasNull(topicType, topicTitle, startTime, place, content)) {
            log.error("添加主题|TopicInfoService|addTopic|params:topicType={},topicTitle={},startTime={},place={}", topicType, topicTitle, startTime, place);
            throw new OnlineRuntimeException("PARAM_ERROR", "基本参数传入存在空值!");
        }

        List<ImgUrlVO> imgUrlVOs = topicInfoVO.getImgUrls();
        List<CityVO> cityVOs = topicInfoVO.getCities();
        List<SchoolVO> schoolVOs = topicInfoVO.getSchools();

        TopicInfoPO topicInfoPO = new TopicInfoPO(topicTitle, topicType, ifLine, startTime, place);
        topicInfoPO.setCreatemanid(createmanId);
        topicInfoMapper.insert(topicInfoPO);
        int topicId = topicInfoPO.getTopicId();
        topicInfoPO.setCreatetime(new Date());
        topicInfoPO.setTopicId(topicId);
        TopicInfoImgPO topicInfoImgPO = new TopicInfoImgPO();
        BeanUtils.copyProperties(topicInfoPO, topicInfoImgPO);
//        TopicInfoImgPO topicInfoImgPO=  topicInfoMapper.queryTopicInfoById(String.valueOf(topicId));
//        List<TopicSchoolInfoPO> topicSchoolInfoPOs = new ArrayList<TopicSchoolInfoPO>();
        //新增topic_city_info表 或者 topic_school_info表
        if (TopicInfoEnum.SCHOOL.getCode() == topicType) {
            if (ObjectUtils.isEmpty(schoolVOs)) {
                throw new OnlineRuntimeException("PARAM_ERROR", "学校列表传入为空!");
            }
            iTopicSchoolInfoService.addSchool(topicId, schoolVOs);
        } else {
            if (ObjectUtils.isEmpty(cityVOs)) {
                throw new OnlineRuntimeException("PARAM_ERROR", "城市列表传入为空!");
            }
            iTopicCityInfoService.addCities(topicId, cityVOs);
        }
        //新增topic_detaill_info表
        iTopicDetailInfoService.insert(topicId, content);
        //新增topic_img_info表
        if (ObjectUtils.isNotEmpty(imgUrlVOs) && imgUrlVOs.size() > 0) {
            iTopicImgInfoService.insert(topicId, imgUrlVOs);
        }
//        if (ObjectUtils.isNotEmpty(schoolVOs) && schoolVOs.size() > 0) {
//            cityVOs = getCityVOWhenSchool(schoolVOs);
//        }
//        //放入一条缓存
//        for (CityVO cityVO : cityVOs) {
//            //处理数据
//            topicInfoImgPO.setCityId(cityVO.getCityId());
//            topicInfoImgPO.setAreaName(cityVO.getCityName());
//            topicInfoImgPO.setSchoolId(String.valueOf(cityVO.getSchoolId()));
//            topicInfoImgPO.setSchoolName(cityVO.getSchooName());
//            if (TopicInfoEnum.SCHOOL.getCode() == topicType && ObjectUtils.isNotNull(cityVO.getSchooName())) {
//                topicInfoImgPO.setTopicTitle(topicTitle + "【" + cityVO.getSchooName() + "】");
//            }else if(ObjectUtils.isNotNull(cityVO.getCityName())){
//                topicInfoImgPO.setTopicTitle(topicTitle + "【" + cityVO.getCityName() + "】");
//            }
//            Map<String, String> map = putTopInfoToMap(topicInfoImgPO);
//            //处理全国数据
//            cacheManagerService.addHashMutil("topic:" + topicId, map);
//            cacheManagerService.zadd(JIUYE + "0", getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            cacheManagerService.zadd(JIUYE + "0" + "_" + topicType, getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            //处理指定缓存
//            Set<String> zSetDesc = cacheManagerService.getZSetDesc(JIUYE + cityVO.getCityId().toString(), 0, DATAFROMDB);
//            if (!ObjectUtils.isEmpty(zSetDesc)) {
//                //删除最后一条缓存
//                if (zSetDesc.size() >= DATAFROMDB) {
//                    cacheManagerService.zremrangebyrank(JIUYE + String.valueOf(cityVO.getCityId()), zSetDesc.size() - 1, zSetDesc.size() - 1);
//                }
//                //插入一条缓存
//                cacheManagerService.zadd(JIUYE + String.valueOf(cityVO.getCityId()), getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            }
//            Set<String> cityTopicTypeKey = cacheManagerService.getZSetDesc(JIUYE + cityVO.getCityId().toString() + "_" + topicType, 0, DATAFROMDB);
//            if (!ObjectUtils.isEmpty(cityTopicTypeKey)) {
//                //删除最后一条缓存
//                if (cityTopicTypeKey.size() >= DATAFROMDB) {
//                    cacheManagerService.zremrangebyrank(JIUYE + String.valueOf(cityVO.getCityId()) + "_" + topicType, cityTopicTypeKey.size() - 1, cityTopicTypeKey.size() - 1);
//                }
//                //插入一条缓存
//                cacheManagerService.zadd(JIUYE + String.valueOf(cityVO.getCityId() + "_" + topicType), getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            }
//        }
    }

    /**
     * 修改主題
     *
     * @param topicInfoVO 参数对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateTopic(TopicInfoVO topicInfoVO) {
        log.info("修改主題|TopicInfoService|updateTopic|params:topicInfoVO={}", topicInfoVO);

        //获取参数并验证非空
        Integer topicId = topicInfoVO.getTopicId();
        Integer topicType = topicInfoVO.getTopicType();
        String topicTitle = topicInfoVO.getTopicTitle();
        Integer ifLine = topicInfoVO.getIfLine();
        Date startTime = topicInfoVO.getStarttime();
        String place = topicInfoVO.getPlace();
        String content = topicInfoVO.getContent();
        Date createtime = topicInfoVO.getCreatetime();
        if (ObjectUtils.hasNull(topicId, topicType, topicTitle, startTime, place, content, createtime)) {
            log.error("修改主題|TopicInfoService|updateTopic|params:topicType={},topicTitle={},startTime={},place={},createtime={}", topicType, topicTitle, startTime, place, createtime);
            throw new OnlineRuntimeException("PARAM_ERROR", "基本参数传入存在空值!");
        }

        List<ImgUrlVO> imgUrlVOs = topicInfoVO.getImgUrls();
        List<CityVO> cityVOs = topicInfoVO.getCities();
        List<SchoolVO> schoolVOs = topicInfoVO.getSchools();

        TopicInfoPO topicInfoPO = new TopicInfoPO(topicTitle, topicType, ifLine, startTime, place);
        topicInfoPO.setTopicId(topicId);
        topicInfoPO.setCreatetime(createtime);
        topicInfoPO.setTopicId(topicId);
        topicInfoMapper.updateByPrimaryKey(topicInfoPO);
        TopicInfoImgPO topicInfoImgPO = new TopicInfoImgPO();
        BeanUtils.copyProperties(topicInfoPO, topicInfoImgPO);
        //修改topic_city_info表 或者 topic_school_info表
        if (TopicInfoEnum.SCHOOL.getCode() == topicType) {
            if (ObjectUtils.isEmpty(schoolVOs)) {
                throw new OnlineRuntimeException("PARAM_ERROR", "学校列表传入为空!");
            }
            iTopicSchoolInfoService.updateSchool(topicId, schoolVOs);
        } else {
            if (ObjectUtils.isEmpty(cityVOs)) {
                throw new OnlineRuntimeException("PARAM_ERROR", "城市列表传入为空!");
            }
            iTopicCityInfoService.updateCities(topicId, cityVOs);
        }
        //修改topic_detaill_info表
        iTopicDetailInfoService.updateByTopicId(topicId, content);
        //修改topic_img_info表
        if (ObjectUtils.isNotEmpty(imgUrlVOs) && imgUrlVOs.size() > 0) {
            iTopicImgInfoService.updateByTopicId(topicId, imgUrlVOs);
        } else {
            iTopicImgInfoService.deleteImgByTopicId(topicId);
        }
        //修改删除状态为未删除
        topicInfoMapper.updateIfDel(topicId,0);
//        if (ObjectUtils.isNotEmpty(schoolVOs) && schoolVOs.size() > 0) {
//            cityVOs = getCityVOWhenSchool(schoolVOs);
//        }
////        List<CityVO> cities = iTopicCityInfoService.getCitiesByTopicId(topicId);
//        for (CityVO cityVO : cityVOs) {
//            //处理数据
//            topicInfoImgPO.setCityId(cityVO.getCityId());
//            topicInfoImgPO.setAreaName(cityVO.getCityName());
//            topicInfoImgPO.setSchoolId(String.valueOf(cityVO.getSchoolId()));
//            topicInfoImgPO.setSchoolName(cityVO.getSchooName());
//            if (TopicInfoEnum.SCHOOL.getCode() == topicType && ObjectUtils.isNotNull(cityVO.getSchooName())) {
//                topicInfoImgPO.setTopicTitle(topicTitle + "【" + cityVO.getSchooName() + "】");
//            }else if(ObjectUtils.isNotNull(cityVO.getCityName())){
//                topicInfoImgPO.setTopicTitle(topicTitle + "【" + cityVO.getCityName() + "】");
//            }
//            Map<String, String> map = putTopInfoToMap(topicInfoImgPO);
//            cacheManagerService.addHashMutil("topic:" + topicId, map);
//            //处理全国缓存
//            cacheManagerService.zrem(JIUYE +"0","topic:"+topicId);
//            cacheManagerService.zadd(JIUYE + "0", getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            cacheManagerService.zrem(JIUYE + "0" + "_" + topicType,"topic:"+topicId);
//            cacheManagerService.zadd(JIUYE + "0" + "_" + topicType, getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            //删除现有缓存
//            if (ObjectUtils.isNotNull(cities)){
//                for (CityVO city: cities) {
//                    //删除未加主题类型的主题信息
//                    cacheManagerService.zrem(JIUYE + city.getCityId().toString(),"topic:"+topicId);
//                }
//            }
//            //处理指定缓存
//            Set<String> zSetDesc = cacheManagerService.getZSetDesc(JIUYE + cityVO.getCityId().toString(), 0, DATAFROMDB);
//            if (!ObjectUtils.isEmpty(zSetDesc)) {
//                //如果超过限额,删除最后一条缓存
//                if (zSetDesc.size() >= DATAFROMDB) {
//                    cacheManagerService.zremrangebyrank(JIUYE + String.valueOf(cityVO.getCityId()), zSetDesc.size() - 1, zSetDesc.size() - 1);
//                }
//                //插入一条缓存
//                cacheManagerService.zadd(JIUYE + String.valueOf(cityVO.getCityId()), getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            }
//
//            //删除现有缓存
//            if (ObjectUtils.isNotNull(cities)){
//                for (CityVO city: cities) {
//                    //删除加了主题类型的主题信息
//                    cacheManagerService.zrem(JIUYE + city.getCityId().toString() + "_" + topicType,"topic:"+topicId);
//                }
//            }
//            //处理指定缓存
//            Set<String> cityTopicTypeKey = cacheManagerService.getZSetDesc(JIUYE + cityVO.getCityId().toString() + "_" + topicType, 0, DATAFROMDB);
//            if (!ObjectUtils.isEmpty(cityTopicTypeKey)) {
//                //如果超过限额,删除最后一条缓存
//                if (cityTopicTypeKey.size() >= DATAFROMDB) {
//                    cacheManagerService.zremrangebyrank(JIUYE + String.valueOf(cityVO.getCityId()) + "_"  + topicType, cityTopicTypeKey.size() - 1, cityTopicTypeKey.size() - 1);
//                }
//                //插入一条缓存
//                cacheManagerService.zadd(JIUYE + String.valueOf(cityVO.getCityId() + "_" + topicType), getDate(topicInfoImgPO.getCreatetime()), "topic:" + String.valueOf(topicId));
//            }
//        }
    }

    /**
     * 根据城市id查询对应专题
     *
     * @param page 分页查询参数,cityId 城市id  pageNo当前页号,pageSize分页大小
     * @return
     */
    public Page<Object> getTopicInfoByLocation(Page page) {
//        int pageSize = page.getPageSize();
//        //以cityI作为key vadlue 为所有topicId的集合
//        String cityId = JIUYE + page.getParams().get("cityId").toString();
//        //获取第一条记录
//        Set<String> sets = cacheManagerService.getZSetDesc(cityId, 0, 0);
//        log.info("getTopicInfoByLocation缓存数据情况|param: sets={}", sets);
//        //开始位置
//        int start = (Integer.valueOf(page.getPageNo()) - 1) * Integer.valueOf(page.getPageSize());
//        //结束位置
//        int end = start + Integer.valueOf(page.getPageSize()) - 1;
//        //记录为空走数据库,加锁
//        List<TopicInfoImgPO> topInfos = null;
//        if (sets == null || sets.size() == 0) {
//            lock.lock();
//            try {
//                if (sets != null && sets.size() != 0) {
//                    topInfos = getCache(cityId, start, end, page, 0);
//                } else {//从数据库取数据
//                    page.setPageSize(DATAFROMDB);//默认一次拉50条数据,
//                    topInfos = getFromDbToCache(cityId, page, 0);//cityId为key
//                }
//            } finally {
//                lock.unlock();
//            }
//        } else {//从缓存取数据
//            //还原默认值
//            page.setPageSize(pageSize);
//            topInfos = getCache(cityId, start, end, page, 0);
//        }
//        //恢复pageSize
//        page.setPageSize(pageSize);
//        //处理第一页的数据显示10条
//        if (topInfos != null && topInfos.size() != 0&&Integer.valueOf(page.getPageNo()) == 1 && topInfos.size() >= Integer.valueOf(page.getPageSize())) {
//            List<TopicInfoImgPO> list = topInfos.subList(0, Integer.valueOf(page.getPageSize()) );
//            page.setResults(CopyVoPo.copyList(list, TopicInfoImgVO.class));
//            page.setTotalRecord(list.size());
//        }else{
//            page.setResults( CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
//            page.setTotalRecord(topInfos.size());
//        }
        List<TopicInfoImgPO> topInfos = topicInfoMapper.getTopicInfoByLocation(page);
        page.setResults(CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
        return page;
    }


    public long getDate(Date date) {
        long millionSeconds = date.getTime() / 1000;//毫秒
        return millionSeconds;

    }

    /**
     * 根据城市id和专题类别查询
     *
     * @param page topicType  类型0 招聘会 1 校园专题 2公务员  cityId 城市id  pageNo当前页号,pageSize分页大小
     * @return
     */
    public Page<Object> getTopicInfoList(Page page) {
        if (page.getParams().get("topicType").equals("1")) {//校园招聘
            List<List<TopicInfoImgVO>> results = new ArrayList<List<TopicInfoImgVO>>();
            //校内
            List<TopicInfoImgVO> innerSchoolsTopicInfos = null;
            //校外
            List<TopicInfoImgVO> outSchoolsTopicInfos = null;
            /***目前不走缓存 one 无城市***/
            List<TopicInfoImgVO> notCityList = null;
            if (page.getParams().get("cityId").toString().equals("0")) {
                List<TopicInfoImgPO> schoolList = topicInfoMapper.getTopicInfoByInnerOrOutList(page);
                notCityList = CopyVoPo.copyList(schoolList, TopicInfoImgVO.class);
                page.setResults(notCityList);
                return page;
            }
            /*** 目前不走缓存 two 校内校外***/
            Map<String, Object> parmas = page.getParams();
            parmas.put("status", 0);
            page.setParams(parmas);
            List<TopicInfoImgPO> outlist = topicInfoMapper.getTopicInfoByInnerOrOutList(page);
            parmas.put("status", 1);
            page.setParams(parmas);
            List<TopicInfoImgPO> innerlist = topicInfoMapper.getTopicInfoByInnerOrOutList(page);
            outSchoolsTopicInfos = CopyVoPo.copyList(outlist, TopicInfoImgVO.class);
            innerSchoolsTopicInfos = CopyVoPo.copyList(innerlist, TopicInfoImgVO.class);
            results.add(innerSchoolsTopicInfos);
            results.add(outSchoolsTopicInfos);
            page.setResults(results);
            return page;
        }
        /***three 公务员和招聘会***/
        List<TopicInfoImgPO> topInfos = topicInfoMapper.getTopicInfoList(page);
        page.setResults(CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
        return page;
//        int pageSize = page.getPageSize();
//        //以cityId_topicType作为key value 为所有topicId的集合
//        String cityTopicKey = JIUYE + page.getParams().get("cityId") + "_" + page.getParams().get("topicType");
//        //获取第一条记录
//        Set<String> sets = cacheManagerService.getZSetDesc(cityTopicKey, 0, 0);
//        log.info("getTopicInfoList缓存数据|param: sets={}", sets);
//        //开始位置
//        int start = (Integer.valueOf(page.getPageNo()) - 1) * Integer.valueOf(page.getPageSize());
//        //结束位置
//        int end = start + Integer.valueOf(page.getPageSize()) - 1;
//        //记录为空走数据库,加锁
//        List<TopicInfoImgPO> topInfos = null;
//        if (sets == null || sets.size() == 0) {
//            lock.lock();
//            try {
//                if (sets != null && sets.size() != 0) {
//                    //还原默认值
//                    page.setPageSize(pageSize);
//                    topInfos = getCache(cityTopicKey, start, end, page, 1);
//                } else {//从数据库取数据
//                    page.setPageSize(DATAFROMDB);//默认一次拉50条数据
//                    topInfos = getFromDbToCache(cityTopicKey, page, 1);//cityTopicKey 为key
//                }
//            } finally {
//                lock.unlock();
//            }
//        } else {//从缓存取数据
//            //还原默认值
//            page.setPageSize(pageSize);
//            topInfos = getCache(cityTopicKey, start, end, page, 1);
//        }
//        //恢复pageSize
//        page.setPageSize(pageSize);
//        //封装数据返回给前台
//        if (topInfos != null && topInfos.size() != 0 && Integer.valueOf(page.getPageNo()) == 1 && topInfos.size() >= Integer.valueOf(page.getPageSize())) {//处理第一页的数据显示10条
//            topInfos = topInfos.subList(0, Integer.valueOf(page.getPageSize()));
//            page.setResults(CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
//            page.setTotalRecord(topInfos.size());
//        }else{
//            page.setResults(CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
//            page.setTotalRecord(topInfos.size());
//        }
    }


    /**
     * 从缓存取数据
     *
     * @param cityTopicKey key
     * @param start        开始位置
     * @param end          结束位置
     *                     1 @param type         0  getTopicInfoByLocation,1  getTopicInfoList
     * @return
     */
    private List<TopicInfoImgPO> getCache(String cityTopicKey, Integer start, Integer end, Page page, int type) {
        log.info("从缓存取数据getCache|param: cityTopicKey={},start={},end={}", cityTopicKey, start, end);
        List<TopicInfoImgPO> topInfos = new ArrayList<TopicInfoImgPO>();
        Set<String> sets = cacheManagerService.getZSetDesc(cityTopicKey, start, end);
        if (sets == null || sets.size() < Integer.valueOf(page.getPageSize())) {
            if (type == 1) {
                topInfos = topicInfoMapper.getTopicInfoList(page);
            } else {
                topInfos = topicInfoMapper.getTopicInfoByLocation(page);
            }
            return topInfos;
        }
        log.info("得到缓存的数据getCache|param: sets={}", sets.toString());
        for (String set : sets) {
            Map<String, String> map = cacheManagerService.hGetAll(set);
            if (map == null || map.size() == 0) {
                //根据topid查询
                set = set.substring(set.indexOf(":") + 1);
                TopicInfoImgPO top = topicInfoMapper.queryTopicInfoById(set);
                map = putTopInfoToMap(top);
            }
//            TopicInfoImgPO topic = EntityUtils.hashToObject(map, TopicInfoImgPO.class);
            TopicInfoImgPO topic = mapToInfo(map);
            topInfos.add(topic);
        }
        return topInfos;
    }

    /**
     * 从数据库取数据to缓存
     *
     * @param cityTopicKey 放缓存的key
     * @param page         分页信息
     * @param type         0  getTopicInfoByLocation,1  getTopicInfoList
     */
    private List<TopicInfoImgPO> getFromDbToCache(String cityTopicKey, Page page, int type) {
        log.info("将数据库的数据放入缓存getFromDbToCache|param: cityTopicKey={},page={},type={}", cityTopicKey, page, type);
        List<TopicInfoImgPO> topInfos;
        if (type == 1) {
            topInfos = topicInfoMapper.getTopicInfoList(page);
        } else {
            topInfos = topicInfoMapper.getTopicInfoByLocation(page);
        }
        for (TopicInfoImgPO topInfo : topInfos) {
            Map<String, String> mp = putTopInfoToMap(topInfo);
            //以topic:topicId为key,value为map,map存放的为数据库一条记录
            cacheManagerService.addHashMutil("topic:" + topInfo.getTopicId(), mp);
            //以cityId_topicType作为key value 为所有topicId的集合
            cacheManagerService.zadd(cityTopicKey, getDate(topInfo.getCreatetime()), "topic:" + topInfo.getTopicId());
        }
        return topInfos;
    }

    /**
     * 组合数据
     *
     * @param topInfo
     * @return
     */
    private Map<String, String> putTopInfoToMap(TopicInfoImgPO topInfo) {
        Map<String, String> mp = new HashMap<String, String>();
        if (null != topInfo && null != topInfo.getTopicId()) {
            mp.put("topicId", topInfo.getTopicId().toString());
        }
        if (null != topInfo && null != topInfo.getTopicTitle()) {
            mp.put("topicTitle", topInfo.getTopicTitle().toString());
        }
        if (null != topInfo && null != topInfo.getIfLine()) {
            mp.put("ifLine", topInfo.getIfLine().toString());
        }
        if (null != topInfo && null != topInfo.getStarttime()) {// 修改时间问题
            mp.put("starttime", DateFormatUtils.format(topInfo.getStarttime(), "yyyy-MM-dd HH:mm:ss"));
        }
        if (null != topInfo && null != topInfo.getCreatetime()) {
            mp.put("createtime", DateFormatUtils.format(topInfo.getCreatetime(), "yyyy-MM-dd HH:mm:ss"));
        }
        if (null != topInfo && null != topInfo.getState()) {
            mp.put("state", topInfo.getState().toString());
        }
        if (null != topInfo && null != topInfo.getImgUrl()) {
            mp.put("imgUrl", topInfo.getImgUrl().toString());
        }
        if (null != topInfo && null != topInfo.getIsLogo()) {
            mp.put("isLogo", topInfo.getIsLogo().toString());
        }
        if (null != topInfo && null != topInfo.getImgId()) {
            mp.put("imgId", topInfo.getImgId().toString());
        }
        if (null != topInfo && null != topInfo.getPlace()) {
            mp.put("place", topInfo.getPlace().toString());
        }
        if (null != topInfo && null != topInfo.getSchoolName()) {
            mp.put("schoolName", topInfo.getSchoolName().toString());
        }
        if (null != topInfo && null != topInfo.getSchoolId()) {
            mp.put("schoolId", topInfo.getSchoolId().toString());
        }
        if (null != topInfo && null != topInfo.getCityId()) {
            mp.put("cityId", topInfo.getCityId().toString());
        }
        if (null != topInfo && null != topInfo.getAreaName()) {
            mp.put("areaName", topInfo.getAreaName().toString());
        }
        if (null != topInfo && null != topInfo.getTopicType()) {
            mp.put("topicType", topInfo.getTopicType().toString());
        }
        return mp;
    }

    /**
     * 组合数据
     *
     * @param
     * @return
     */
    private TopicInfoImgPO mapToInfo(Map<String, String> mp) {
        final DateTimeFormatter format2 = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        final TopicInfoImgPO topicInfoImgPO = new TopicInfoImgPO();
        if (null != mp && mp.size() > 0 && null != mp.get("topicId")) {
            topicInfoImgPO.setTopicId(Integer.parseInt(mp.get("topicId")));
        }
        if (null != mp && mp.size() > 0 && null != mp.get("topicTitle")) {
            topicInfoImgPO.setTopicTitle(mp.get("topicTitle"));
        }
        if (null != mp && mp.size() > 0 && null != mp.get("ifLine")) {
            topicInfoImgPO.setIfLine(Integer.parseInt(mp.get("ifLine")));
        }
        if (null != mp && mp.size() > 0 && null != mp.get("starttime")) {
            topicInfoImgPO.setStarttime(DateTime.parse(mp.get("starttime"), format2).toDate());
        }
        if (null != mp && mp.size() > 0 && null != mp.get("createtime")) {
            topicInfoImgPO.setCreatetime(DateTime.parse(mp.get("createtime"), format2).toDate());
        }
        if (null != mp && mp.size() > 0 && mp.get("isLogo") != null) {
            topicInfoImgPO.setIsLogo(Integer.parseInt(mp.get("isLogo")));
        }
        if (null != mp && mp.size() > 0 && mp.get("state") != null) {
            topicInfoImgPO.setState(Byte.parseByte(mp.get("state")));
        }
        if (null != mp && mp.size() > 0 && mp.get("imgUrl") != null) {
            topicInfoImgPO.setImgUrl(mp.get("imgUrl"));
        }
        if (null != mp && mp.size() > 0 && mp.get("imgId") != null) {
            topicInfoImgPO.setImgId(Integer.parseInt(mp.get("imgId")));
        }
        if (null != mp && mp.size() > 0 && mp.get("place") != null) {
            topicInfoImgPO.setPlace(mp.get("place"));
        }
        if (null != mp && mp.size() > 0 && mp.get("schoolId") != null) {
            topicInfoImgPO.setSchoolId(mp.get("schoolId"));
        }
        if (null != mp && mp.size() > 0 && mp.get("schoolName") != null) {
            topicInfoImgPO.setSchoolName(mp.get("schoolName"));
        }
        if (null != mp && mp.size() > 0 && mp.get("cityId") != null) {
            topicInfoImgPO.setCityId(Integer.valueOf(mp.get("cityId")));
        }
        if (null != mp && mp.size() > 0 && mp.get("areaName") != null) {
            topicInfoImgPO.setAreaName(mp.get("areaName"));
        }
        if (null != mp && mp.size() > 0 && mp.get("topicType") != null) {
            topicInfoImgPO.setTopicType(Integer.valueOf(mp.get("topicType")));
        }
        return topicInfoImgPO;
    }

    /**
     * 根据城市名称 学校名称 专题名称搜索
     *
     * @param page condition 搜索条件pageNo当前页号,pageSize分页大小
     * @return
     */
    public Page<Object> searchTopic(Page page) {
        List<TopicInfoImgPO> topInfos = topicInfoMapper.searchTopic(page);
        page.setResults(CopyVoPo.copyList(topInfos, TopicInfoImgVO.class));
        return page;
    }

    /**
     * 修改state状态,结束发布
     *
     * @param topicId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTopicState(Integer topicId) {
        log.info("查看变更topicId[TopicInfoService][updateTopicState]param{topicId :" + topicId + "}");
        Integer status = TopicInfoStateEnum.END.getCode();
        int count = topicInfoMapper.updataTopicInfoState(status.byteValue(), topicId);
        if (count == 1) {
            log.info("结束发布成功[TopicInfoService][updateTopicState]param{status :" + status + "}");
        } else {
            log.info("结束发布失败[TopicInfoService][updateTopicState]param{status :" + status + "}");
        }
    }

    /**
     * 根据 topicId 删除专题
     *
     * @param topicId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer removeTopicByTopicId(Integer topicId) {
        //删除 base 库
        int changeNo = topicInfoMapper.deleteBaseByTopicId(topicId);
        //删除 city 库
        iTopicCityInfoService.deleteCityByTopicId(topicId);
        //删除 detail 库
        iTopicDetailInfoService.deleteDetailByTopicId(topicId);
        //删除 img 库
        iTopicImgInfoService.deleteImgByTopicId(topicId);
        //删除 school 库
        iTopicSchoolInfoService.deleteSchoolByTopicId(topicId);
        return changeNo;
    }

    /**
     *  方法removeTopicByTopicIdAndIfDel的功能描述:根据TopicId修改状态
     *  方法改动记录:
     *
     *  @params : [topicId]
     *  @return  java.lang.Integer
     *  @throw
     *  @version :  V1.0.0
     *  @since   :  17/2/13 上午10:49
     *  AUTHOR   :  gongzhijie
     **/
    @Override
    public Integer removeTopicByTopicIdAndIfDel(Integer topicId) {
        log.info("删除专题|TopicInfoService|removeTopicByTopicIdAndIfDel:topicId={}", topicId);
        return topicInfoMapper.updateIfDel(topicId,1); //删除标志 0 未删除 1删除
    }

    @Override
    public void topOrUnTopTopic(Integer topicId, Integer topState) {
        log.info("置顶专题|TopicInfoService|topOrUnTopTopic:topicId={},topState={}", topicId, topState);
        if (ObjectUtils.isNull(topicId) || topState > 1 || topState < 0) {
            log.error("置顶专题参数异常|TopicInfoService|topOrUnTopTopic:topicId={},topState={}", topicId, topState);
            throw new OnlineRuntimeException("PARAM_ERROR", "基本参数传入有误!");
        }
        int currentSort = 0;
        if (topState == 1) {
            currentSort = topicInfoMapper.getCurrentMaxSort() + 1;
        }
        int influenceLow = topicInfoMapper.topTopicByIdAndState(topicId, topState, currentSort);
        if (influenceLow > 1) {
            log.error("置顶专题数据库异常|TopicInfoService|topOrUnTopTopic:influenceLow={}", influenceLow);
            throw new OnlineRuntimeException("DATA_ERROR", "置顶专题修改数据库异常!");
        }
    }

    private List<CityVO> getCityVOWhenSchool(List<SchoolVO> schoolVOs) {
        List<CityVO> cityVOs = new ArrayList<CityVO>();
        for (SchoolVO schoolVO : schoolVOs) {
            if (ObjectUtils.isNull(schoolVO)) {
                continue;
            }
            CityVO cityVo = new CityVO();
            String cityId = schoolVO.getCityId();
            cityVo.setCityId(Integer.valueOf(cityId));
            cityVo.setSchooName(schoolVO.getSchoolName());
            cityVo.setSchoolId(schoolVO.getSchoolId());
            cityVOs.add(cityVo);
        }
        return cityVOs;
    }


}